﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

namespace GameToolkit
{
    [AddComponentMenu("Navigation/Runtime NavMeshModifyVolume")]
    public class NavMeshModifyVolume : VolumetricBounds, INavMeshSource
    {
#pragma warning disable CS0649

        [NavAreaType]
        [SerializeField]
        int m_AreaType;

        [HideInInspector]
        [NavAgentType]
        [SerializeField]
        List<int> m_AffectAgents = new List<int>();

        [HideInInspector]
        [SerializeField]
        bool m_IsRuntime;
#pragma warning restore

        protected virtual void OnEnable()
        {
            if (m_IsRuntime)
                RuntimeNavMeshBuilder.AddBuildSource(this);
        }

        protected virtual void OnDisable()
        {
            if (m_IsRuntime)
                RuntimeNavMeshBuilder.RemoveBuildSource(this);
        }

        public bool AffectOnAgent(int agentId)
        {
            if (m_AffectAgents.Count == 1 && m_AffectAgents[0] == -1)
                return true;
            else
                return m_AffectAgents.Contains(agentId);
        }

        public void GetBuildSource(int areaType, ICollection<NavMeshBuildSource> sources)
        {
            var mcenter = transform.TransformPoint(m_BoundsCenter);
            var scale = transform.lossyScale;
            var msize = new Vector3(m_BoundsSize.x * Mathf.Abs(scale.x), m_BoundsSize.y * Mathf.Abs(scale.y), m_BoundsSize.z * Mathf.Abs(scale.z));

            var src = new NavMeshBuildSource();
            src.shape = NavMeshBuildSourceShape.ModifierBox;
            src.transform = Matrix4x4.TRS(mcenter, transform.rotation, Vector3.one);
            src.size = msize;
            src.area = m_AreaType;
            sources.Add(src);
        }

//#if UNITY_EDITOR
//        public override Color color { get { return new Color(1f, 0.4f, 1f); } }
//#endif
    }
}